import { observable, action} from 'mobx'
import axios from "../../../common/request";
import notificationWithIcon from "../../common/notificationWithIcon";

class ExhibitorStore {
    @observable loading=false;
    @observable imgLoading = false
    @observable imgLoading2 = false
    @observable imageUrl = ''
    @observable imageUrl2 = ''
    @observable current=0
    @observable expoId=-1;
    @observable hasRe=0

    @observable editIndex=-1;
    @observable pageTotal=0

    @observable exhibitorList=[]

    @observable defaultFileList=[]
    hasProps=false

    standInfo={}

    id=''
    expoName=''
    hallId=-1

    @observable hallOptions=[]

    @observable expoData=[]

    @observable halls=[]
    @observable areas=[]

    @observable exhibitorInfo={}

    fileListLength=0;



    actions={
        verifyCode:action((form)=>{
            form.validateFields(['code'],(err, values) => {
                if(!err){
                    axios.post('/api/expo/participantLogin', {
                        verifyCode:values['code'],
                    })
                        .then((response) => {
                            if (response.data.status.code === 1) {
                                this.id=response.data.result.id;
                                this.expoName=response.data.result.expoName
                                axios.get('/api/expo/hallName?expoId='+this.id)
                                    .then((response) => {
                                        if (response.data.status.code === 1) {
                                            if(this.hallOptions>0) {
                                                this.hallOptions.splice(0, this.hallOptions.length)
                                            }
                                            response.data.result.hall.map(h=>this.hallOptions.push({
                                                value:h.id,
                                                label:h.hallName,
                                                isLeaf:false,
                                            }))
                                        }
                                        else {
                                            notificationWithIcon('error', response.data.status.message, "")
                                        }
                                    })
                                    .catch(function (error) {
                                        console.log(error)
                                        notificationWithIcon('error', '发生错误', error.response)
                                    });
                                this.current++;
                            }
                            else {
                                notificationWithIcon('error', response.data.status.message, "")
                            }
                        })
                        .catch(function (error) {
                            console.log(error)
                            notificationWithIcon('error', '发生错误', error.response)
                        });
                }
            });
        }),
        loadStand:action((selectedOptions)=>{
            const targetOption = selectedOptions[selectedOptions.length - 1];
            targetOption.loading = true;
            if(selectedOptions.length==1) {
                axios.get('/api/expo/areaName?hallId=' + targetOption.value)
                    .then((response) => {
                        if (response.data.status.code === 1) {
                            let children = []
                            response.data.result.area.map(a => children.push({
                                value: a.id,
                                label: a.areaName,
                                isLeaf: false,
                            }))
                            targetOption.children = children
                            targetOption.loading = false;
                        }
                        else {
                            notificationWithIcon('error', response.data.status.message, "")
                        }
                    })
                    .catch(function (error) {
                        console.log(error)
                        notificationWithIcon('error', '发生错误', error.response)
                    });
            }else if(selectedOptions.length==2) {
                axios.get('/api/expo/stand?areaId=' + targetOption.value)
                    .then((response) => {
                        if (response.data.status.code === 1) {
                            let children = []
                            response.data.result.stand.map(s => children.push({
                                value: s.id,
                                word:s.word,
                                number:s.number,
                                label: s.word+s.number,
                            }))
                            targetOption.children = children
                            targetOption.loading = false;
                        }
                        else {
                            notificationWithIcon('error', response.data.status.message, "")
                        }
                    })
                    .catch(function (error) {
                        console.log(error)
                        notificationWithIcon('error', '发生错误', error.response)
                    });
            }
        }),
        standChange:action((value, selectedOptions)=>{
            if(selectedOptions.length==0||selectedOptions[2]==null){
                this.hasRe=-3;
                return;
            }
            this.hasRe=-2;
            let v=selectedOptions[2].value;
            axios.get('/api/expo/standRepeat?standId=' + v)
                .then((response) => {
                    if (response.data.status.code === 1) {
                        this.hasRe=1;
                    }
                    else {
                        this.hasRe=-1;
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    notificationWithIcon('error', '发生错误', error.response)
                });
        }),
        getBase64:action((img, callback) =>{
            const reader = new FileReader();
            reader.addEventListener('load', () => callback(reader.result));
            reader.readAsDataURL(img);
        }),
        handleImgChange:action((info)=>{
            if (info.file.status === 'uploading') {
                this.loading=true;
                return;
            }
            if (info.file.status === 'done') {
                // Get this url from response in real world.
                this.actions.getBase64(info.file.originFileObj, imageUrl => {
                    this.imageUrl=imageUrl;
                    this.imgLoading=false;
                });
                //console.log(info.file.response.result.key)
                //this.props.getKey(info.file.response.result.key)
            }
        }),
        handleImgChange2:action((info)=>{
            if (info.file.status === 'uploading') {
                this.loading2=true;
                return;
            }
            if (info.file.status === 'done') {
                // Get this url from response in real world.
                this.actions.getBase64(info.file.originFileObj, imageUrl => {
                    this.imageUrl2=imageUrl;
                    this.imgLoading2=false;
                });
                //console.log(info.file.response.result.key)
                //this.props.getKey(info.file.response.result.key)
            }
        }),
        next:action((form)=>{
            form.validateFields(['companyName','companyAbbreviation','stand','companyImg'],(err, values) => {
                if(!err&&this.hasRe==1){
                    let hallName='';
                    let areaName='';
                    let standWord='';
                    let standNumber='';
                    this.hallOptions.map(hall=>{
                        if(hall.value==values['stand'][0]){
                            hallName=hall.label;
                            hall.children.map(area=>{
                                areaName=area.label;
                                area.children.map(stand=>{
                                    standWord=stand.word;
                                    standNumber=stand.number;
                                })
                            })
                        }
                    });
                    this.standInfo={
                        companyName:values['companyName'],
                        companyAbbreviation:values['companyAbbreviation'],
                        hallId:values['stand'][0],
                        hallName:hallName,
                        areaId:values['stand'][1],
                        areaName:areaName,
                        standId:values['stand'][2],
                        standWord:standWord,
                        standNumber:standNumber,
                        companyImg:values['companyImg'].file.response.result.key,
                    }
                    this.current++;
                }
            });
        }),
        prev:action(()=>{
            this.current--;
        }),
        finish:action((form)=>{
            form.validateFieldsAndScroll(['address', 'companyScope',
                'officialUrl','companyFax','contacts','contactsPhone',
                'contactsEmail','qq','wechat','wechatQrcode',
                'companyIntroduction','serviceIntroduction','caseIntroduction','companyRecruit','participantFile'],(err, values) => {
                if (!err) {
                    let img=''
                    if(values['wechatQrcode']!=undefined&&values['wechatQrcode']!=null){
                        img=values['wechatQrcode'].file.response.result.key;
                    }
                    axios.post('/api/expo/createParticipant', {
                        expoId:this.id,
                        expoName:this.expoName,
                        companyName:this.standInfo.companyName,
                        companyAbbreviation:this.standInfo.companyAbbreviation,
                        hallId:this.standInfo.hallId,
                        hallName:this.standInfo.hallName,
                        areaId:this.standInfo.areaId,
                        areaName:this.standInfo.areaName,
                        standId:this.standInfo.standId,
                        standWord:this.standInfo.standWord,
                        standNumber:this.standInfo.standNumber,
                        companyImg:this.standInfo.companyImg,
                        wechatQrcode:img,
                        address:values['address'],
                        companyScope:values['companyScope'],
                        officialUrl:values['officialUrl'],
                        companyFax:values['companyFax'],
                        contacts:values['contacts'],
                        contactsPhone:values['contactsPhone'],
                        contactsEmail:values['contactsEmail'],
                        qq:values['qq'],
                        wechat:values['wechat'],
                        companyIntroduction:values['companyIntroduction'],
                        serviceIntroduction:values['serviceIntroduction'],
                        caseIntroduction:values['caseIntroduction'],
                        companyRecruit:values['companyRecruit'],
                    })
                        .then((response) => {
                            if (response.data.status.code === 1) {
                                let participantId=response.data.result.participantId;
                                values['participantFile']!=undefined&&values['participantFile'].fileList.map(file=>{
                                    axios.post('/api/expo/participantFile',{
                                        participantId:participantId,
                                        key:file.response.result.key,
                                        fileName:file.response.result.fileName,
                                        fileType:file.response.result.fileType,
                                    })
                                        .then((response) => {
                                            if (response.data.status.code === 1) {

                                            }
                                            else {
                                                notificationWithIcon('error', response.data.status.message, "")
                                            }
                                        })
                                        .catch(function (error) {
                                            console.log(error)
                                            notificationWithIcon('error', '发生错误', error.response)
                                        });
                                })
                                this.current++;
                            }
                            else {
                                notificationWithIcon('error', response.data.status.message, "")
                            }
                        })
                        .catch(function (error) {
                            console.log(error)
                            notificationWithIcon('error', '发生错误', error.response)
                        });


                }
            });
        }),
        hallChange:action((value)=>{
            this.hallId=value;
            axios.get('/api/expo/areaName?hallId='+value)
                .then((response) => {
                    if (response.data.status.code === 1) {
                        if(this.areas.length>0){
                            this.areas.splice(0,this.halls.length)
                        }
                        response.data.result.area.map(h=>this.areas.push({
                            value:h.id,
                            label:h.areaName,
                            isLeaf:false,
                        }))
                        this.areas.map(area=>{
                            axios.get('/api/expo/stand?areaId=' + area.value)
                                .then((response) => {
                                    if (response.data.status.code === 1) {
                                        let children = []
                                        response.data.result.stand.map(s => children.push({
                                            value: s.id,
                                            word:s.word,
                                            number:s.number,
                                            label: s.word+s.number,
                                        }))
                                        area.children = children
                                    }
                                    else {
                                        notificationWithIcon('error', response.data.status.message, "")
                                    }
                                })
                                .catch(function (error) {
                                    console.log(error)
                                    notificationWithIcon('error', '发生错误', error.response)
                                });
                        })
                        axios.get('/api/expo/getParticipantByHallId?hallId=' + value)
                            .then((response) => {
                                if (response.data.status.code === 1) {
                                    if(this.expoData.length>0){
                                        this.expoData.splice(0,this.expoData.length)
                                    }
                                    response.data.result.list.map(l=>this.expoData.push({
                                        id:l.id,
                                        name:l.companyAbbreviation,
                                        standId:l.standId,
                                        areaId:l.areaId,
                                    }));
                                    this.pageTotal=response.data.result.count;
                                }
                                else {
                                    notificationWithIcon('error', response.data.status.message, "")
                                }
                            })
                            .catch(function (error) {
                                console.log(error)
                                notificationWithIcon('error', '发生错误', error.response)
                            });
                    }
                    else {
                        notificationWithIcon('error', response.data.status.message, "")
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    notificationWithIcon('error', '发生错误', error.response)
                });
        }),
        standChanges:action((value, selectedOptions)=>{
            if(selectedOptions.length==0||selectedOptions[1]==null){
                this.hasRe=-3;
                return;
            }
            this.hasRe=-2;
            let v=selectedOptions[1].value;
            axios.get('/api/expo/standRepeat?standId=' + v)
                .then((response) => {
                    if (response.data.status.code === 1) {
                        this.hasRe=1;
                    }
                    else {
                        this.hasRe=-1;
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    notificationWithIcon('error', '发生错误', error.response)
                });
        }),
        delCompany:action((index)=>{
            let id=this.expoData[index].id;
            axios.post('/api/expo/cancelParticipant',{
                participantId:id
            })
                .then((response) => {
                    if (response.data.status.code === 1) {
                        this.expoData.splice(index,1);
                    }
                    else {
                        notificationWithIcon('error', response.data.status.message, "")
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    notificationWithIcon('error', '发生错误', error.response)
                });
        }),
        saveCompany:action((index,form)=>{
            form.validateFields([`stand[${index}]`],(err, values) => {
                let stand=values.stand[index]
                if (!err&&this.hasRe==1) {
                    this.hasRe=0;
                    this.editIndex=-1;
                    let areaName='';
                    let word='';
                    let number='';
                    this.areas.map(area=>{
                        if(area.value==stand[0]){
                            areaName=area.label;
                            area.children.map(s=>{
                                if(s.value==stand[1]){
                                    word=s.word;
                                    number=s.number;
                                }
                            });
                        }
                    });
                    let id=this.expoData[index].id;
                    axios.post('/api/expo/modifyParticipantStand',{
                        participantId:id,
                        areaId:stand[0],
                        areaName:areaName,
                        standId:stand[1],
                        word:word,
                        number:number,
                    })
                        .then((response) => {
                            if (response.data.status.code === 1) {
                                this.expoData[index].areaId=stand[0];
                                this.expoData[index].standId=stand[1];
                            }
                            else {
                                notificationWithIcon('error', response.data.status.message, "")
                            }
                        })
                        .catch(function (error) {
                            console.log(error)
                            notificationWithIcon('error', '发生错误', error.response)
                        });
                }
            });
        }),
        setEdit:action((index)=>{
            this.hasRe=0;
            this.editIndex=index;
        }),
        cancelEdit:action(()=>{
            this.hasRe=0;
            this.editIndex=-1;
        }),
        getManageData:action((id)=>{
            this.expoId=id;
            axios.get('/api/expo/hallName?expoId='+id)
                .then((response) => {
                    if (response.data.status.code === 1) {
                        if(this.halls.length>0){
                            this.halls.splice(0,this.halls.length)
                        }
                        response.data.result.hall.map(h=>this.halls.push({
                            id:h.id,
                            value:h.hallName,
                        }))
                    }
                    else {
                        notificationWithIcon('error', response.data.status.message, "")
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    notificationWithIcon('error', '发生错误', error.response)
                });
        }),
        pageChange:action((page)=>{
            axios.get(`/api/expo/getParticipantByHallId?hallId=${this.hallId}&page=${page}`)
                .then((response) => {
                    if (response.data.status.code === 1) {
                        if(this.expoData.length>0){
                            this.expoData.splice(0,this.expoData.length)
                        }
                        response.data.result.list.map(l=>this.expoData.push({
                            id:l.id,
                            name:l.companyAbbreviation,
                            standId:l.standId,
                            areaId:l.areaId,
                        }));
                        this.pageTotal=response.data.result.count;
                    }
                    else {
                        notificationWithIcon('error', response.data.status.message, "")
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    notificationWithIcon('error', '发生错误', error.response)
                });
        }),
        getExhibitorList:action(()=>{
            axios.get('/api/expo/getParticipantsList?status=no')
                .then((response)=> {
                    if(response.data.status.code===1) {
                        if(response.data.result!=undefined) {
                            this.exhibitorList = response.data.result
                        }else{
                            this.exhibitorList  =[];
                        }

                    }
                    else{
                        notificationWithIcon('error',response.data.status.message,"")
                    }
                })
                .catch(function (error) {
                    notificationWithIcon('error',"获取展览列表失败",error.response)
                    console.log(error);
                });
        }),
        getExhibitorDetail:action((id)=>{
            axios.get(`/api/expo/getParticipantsDetail?participantId=${id}`)
                .then((response) => {
                    if (response.data.status.code === 1) {
                        this.exhibitorInfo=response.data.result;
                        this.imageUrl=this.exhibitorInfo.companyImg
                        this.imageUrl2=this.exhibitorInfo.wechatQrcode
                    }
                    else {
                        notificationWithIcon('error', response.data.status.message, "")
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    notificationWithIcon('error', '发生错误', error.response)
                });
            axios.get(`/api/expo/getParticipantFile?participantId=${id}`)
                .then((response) => {
                    if (response.data.status.code === 1) {
                        this.defaultFileList=response.data.result;
                        if(this.defaultFileList!=undefined){
                            this.fileListLength=this.defaultFileList.length;
                        }
                    }
                    else {
                        notificationWithIcon('error', response.data.status.message, "")
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    notificationWithIcon('error', '发生错误', error.response)
                });
            this.hasProps=false
        }),
        clearExhibitorDetail:action(()=>{
            this.exhibitorInfo={}
            this.imageUrl=''
            this.imageUrl2=''
            this.hasProps=true
            this.defaultFileList=[]
            this.fileListLength=0
        }),
        updateInfo:action((form)=>{
            form.validateFieldsAndScroll((err, values) => {
                console.log(values);
                if (!err) {
                    let img1=''
                    if(values['companyImg']!=undefined&&values['companyImg']!=null&&values['companyImg'].file!=undefined){
                        img1=values['companyImg'].file.response.result.key;
                    }else{
                        img1=this.exhibitorInfo.key
                    }
                    let img2=''
                    if(values['wechatQrcode']!=undefined&&values['wechatQrcode']!=null&&values['wechatQrcode'].file!=undefined){
                        img2=values['wechatQrcode'].file.response.result.key;
                    }else{
                        img2=this.exhibitorInfo.qRcodeKey;
                    }
                    axios.post('/api/expo/modifyParticipant', {
                        id:this.exhibitorInfo.id,
                        companyName:values['companyName'],
                        companyAbbreviation:values['companyAbbreviation'],
                        companyImg:img1,
                        wechatQrcode:img2,
                        address:values['address'],
                        companyScope:values['companyScope'],
                        officialUrl:values['officialUrl'],
                        companyFax:values['companyFax'],
                        contacts:values['contacts'],
                        contactsPhone:values['contactsPhone'],
                        contactsEmail:values['contactsEmail'],
                        qq:values['qq'],
                        wechat:values['wechat'],
                        companyIntroduction:values['companyIntroduction'],
                        serviceIntroduction:values['serviceIntroduction'],
                        caseIntroduction:values['caseIntroduction'],
                        companyRecruit:values['companyRecruit'],
                    })
                        .then((response) => {
                            if (response.data.status.code === 1) {
                                let hasErr=false;
                                values['participantFile']!=undefined&&values['participantFile'].fileList.map(file=>{
                                    let status=0;
                                    for(let i in this.defaultFileList){
                                        if(file.response.result.key==this.defaultFileList[i].key){
                                            status=1;
                                            this.defaultFileList[i].status=1;
                                        }
                                    }
                                    if(status==0){
                                        axios.post('/api/expo/participantFile',{
                                            participantId:this.exhibitorInfo.id,
                                            key:file.response.result.key,
                                            fileName:file.response.result.fileName,
                                            fileType:file.response.result.fileType,
                                        })
                                            .then((response) => {
                                                if (response.data.status.code === 1) {

                                                }
                                                else {
                                                    hasErr=true;
                                                    notificationWithIcon('error', response.data.status.message, "")
                                                }
                                            })
                                            .catch(function (error) {
                                                console.log(error)
                                                hasErr=true;
                                                notificationWithIcon('error', '发生错误', error.response)
                                            });
                                    }
                                })
                                for(let i in this.exhibitorInfo){
                                    if(this.exhibitorInfo[i].status==undefined||this.exhibitorInfo[i].status!=1){
                                        let fileId=this.exhibitorInfo[i].fileId;
                                        axios.post('/api/expo/delParticipantFile',{
                                            fileId:fileId,
                                        })
                                            .then((response) => {
                                                if (response.data.status.code === 1) {

                                                }
                                                else {
                                                    hasErr=true;
                                                    notificationWithIcon('error', response.data.status.message, "")
                                                }
                                            })
                                            .catch(function (error) {
                                                console.log(error)
                                                hasErr=true;
                                                notificationWithIcon('error', '发生错误', error.response)
                                            });
                                    }
                                }
                                if(!hasErr){
                                    Modal.confirm({
                                        title: '修改成功',
                                        content:'成功修改信息，是否前去看看自己的展位',
                                        iconType:'check-circle',
                                        okText:'立即前去',
                                        cancelText:'取消',
                                        onOk:()=>window.open(`/exhibition/exhibitor/${this.exhibitorInfo.id}`, '_blank').location,
                                    });
                                }

                            }
                            else {
                                notificationWithIcon('error', response.data.status.message, "")
                            }
                        })
                        .catch(function (error) {
                            console.log(error)
                            notificationWithIcon('error', '发生错误', error.response)
                        });
                }
            });
        }),
        resetCurrent:action(()=>{
            this.actions.clearExhibitorDetail();
            this.current=0;
        }),
        getFileListLength:action(({file,fileList})=>{
            this.fileListLength=fileList.length;
        }),
    }
}

export default new ExhibitorStore()

